import React from 'react'
import config from './config'
import { successMsg } from './common'

const { ipcRenderer } = require('electron')
const formSetRef = React.createRef()

/**
 * 初始化迁移目录
 */
const initMigPath = (context) => {
  const setting = config.getData()
  // console.log(setting)
  if (setting) {
    // console.log(formSetRef.current)
    formSetRef.current.setFieldsValue({
      migPath: setting.migratePath
    })
  }
  listenSelectMigPath(context)
}

/**
 * 打开目录选择框
 */
const openDirDialog = (context) => {
  const data = {
    selectMigPath: context.t('selectMigPath')
  }
  ipcRenderer.send('openDirDialog', data)
}

// 监听
const listenSelectMigPath = (context) => {
  ipcRenderer.removeAllListeners('selectMigPath')
  // 设置迁移目录
  ipcRenderer.on('selectMigPath', (_, migDir) => {
    // console.log(formSetRef.current)
    formSetRef.current.setFieldsValue({
      migPath: migDir
    })
    const setting = config.getData()
    if (setting) {
      setting.migratePath = migDir
      config.writeData(JSON.stringify(setting))
      successMsg(context)
    }
  })
}

export { initMigPath, openDirDialog, formSetRef }
